<template>
  <div>
    <van-address-edit
      :area-list="AreaList"
      show-postal
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @change-detail="onChangeDetail"
      :address-info="getItemById($route.params.editType)"
    />
    <van-button @click="onBackClicked" class="back-address" color="#fff" round size="large">
      <span style="color:#000;">返回地址列表</span>
    </van-button>
    <van-dialog
      @confirm="onConfirm"
      @cancel="onCancel"
      v-model="showDefaultAddress"
      title="是否设置为默认地址"
      show-cancel-button
    />
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import AreaList from '@/utils/area'
// import http from 'axios'

import Vue from 'vue'
import { AddressEdit, Toast, Dialog, Button } from 'vant'
Vue.use(AddressEdit).use(Toast).use(Dialog).use(Button)
export default {
  data() {
    return {
      AreaList,
      addressDetail: '',
      content: {},
      showDefaultAddress: false
    }
  },
  computed: {
    ...mapGetters('addressModule', ['getItemById'])
  },
  methods: {
    ...mapActions('addressModule', ['addArea', 'modifyItem']),
    // edit
    onSave(content) {
      content.addressDetail = this.addressDetail
      content.address = (content.province.substr(0, 2) === content.city.substr(0, 2) ? content.city : content.province + content.city) + content.county + ' ' + this.addressDetail
      // 改变data
      this.content = content
      this.showDefaultAddress = true
    },
    onBackClicked() {
      this.$router.go(-1)
    },
    onChangeDetail(val) {
      if (val) {
        this.addressDetail = val
      } else {
        this.addressDetail = ''
      }
    },
    onConfirm() {
      this.addOrModify(true)
    },
    onCancel() {
      this.addOrModify(false)
    },
    addOrModify(isDefault) {
      if (this.$route.params.editType) {
        // 改
        this.modifyItem({ id: this.$route.params.editType, ...this.content, isDefault }).then(() => {
          Toast({
            message: '修改地址成功~',
            closeOnClick: true
          })
          this.showDefaultAddress = false
          this.$router.replace({
            name: 'Address-list'
          })
        })
      } else {
        // 新增
        // content.id = 'area' + new Date().getTime()
        this.addArea({ ...this.content, isDefault }).then(() => {
          Toast({
            message: '添加地址成功~',
            closeOnClick: true
          })
          this.showDefaultAddress = false
          this.$router.replace({
            name: 'Address-list'
          })
        })
      }
    }
  }
}
</script>

<style>
.back-address {
  width: 92vw;
  height: 40px;
  line-height: 40px;
}
</style>
